<template>
	<view class="u-wrap">
		<z-paging ref="paging" v-model="dataList" @query="queryList" :show-default-loading-more-text="false">
			<template #top>
				<view class="u-search-box">
					<view class="u-search-inner" @click="jumt">
						<u-icon name="search" color="#909399" :size="28"></u-icon>
						<text class="u-search-text">搜索</text>
					</view>
				</view>
				<!-- 广告栏1 begin -->
				<!-- 			<swiper class="ads1" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" circular>
					<swiper-item v-for="(ad, index) in ads1" :key="index">
						<image :src="ad" mode="aspectFill"></image>
					</swiper-item>
				</swiper> -->
			</template>
			<!-- 广告栏1 end -->
			<template #left>
				<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop">
					<view v-for="(item,index) in menuItemPos" :key="index" class="u-tab-item"
						:class="[current == index ? 'u-tab-item-active' : '']" @click.stop="swichMenu(index)">
						<text class="u-line-1">{{item.category_name}}</text>
					</view>
				</scroll-view>
			</template>
			<scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box">
				<!-- 商品 begin -->
				<view class="products-list">
					<view class="products" :class="{'mpd': cartData.length > 0}">
						<view class="product" v-for="(item1, index1) in dataList" :key="index1"
							@click="handleGoodsDetail(item1)">
							<image :src="item1.sku_image" mode="aspectFill" class="image"></image>
							<view class="content">
								<view class="name">{{ item1.goods_name }}</view>
								<view class="description">{{ item1.introduction }}</view>
								<view class="price">
									<view>&yen;{{ item1.price || 0}}</view>
									<Actions :number="item1.currentNum" :materialsFlag="item1.materialsFlag"
										@materials="materialsDetail(item1, index1)" @add="handleCurrentAdd(item1)"
										@minus="handleMinusFromCart(item1)" />
								</view>
								<!-- 商品 end -->
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

		</z-paging>
		<product-modal :visible="visibleShow" :product="productVal" @cancel="visibleShow = false" :cardGoods="cartData"
			@add-to-cart="handleAddToCartInModal"></product-modal>

		<Tabbar cureentPage="shop" />
		<!-- 购物车栏 begin -->
		<cart-bar :cart="cartData" @add="handleCurrentAdd" @minus="handleMinusFromCart" @clear="clearCart" @pay="pay" />
	</view>
</template>
<script>
	import Actions from './components/actions.vue'
	import Tabbar from '@/components/common/Tabbar.vue'
	import productModal from "./components/product-modal.vue"
	import cartBar from "./components/cartbar.vue"
	import request from "@/api/request";
	export default {
		components: {
			Actions,
			Tabbar,
			productModal,
			cartBar
		},
		data() {
			return {
				goodsDto: {
					page: 1,
					page_size: 10,
					category_id: null
				},
				dataList: [],
				cartData: [],
				productVal: {},
				visibleShow: false,
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0,
				current: 0, // 预设当前项的值
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				menuItemPos: [],
				arr: [],
				scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
				timer: null, // 定时器

			}
		},
		onLoad() {
			this.getMenuList()
		},
		onReady() {
			this.getMenuItemTop()
		},
		onShow() {
			// 获取购物车缓存
			this.cartData = uni.getStorageSync('card') || []
		},
		methods: {
			queryList(page, page_size) {
				uni.showLoading({
					title: '加载中...'
				})
				this.goodsDto.page = page
				this.goodsDto.page_size = page_size
				request({
					url: '/kx/Shop/categoryGoodsList',
					method: 'POST',
					data: this.goodsDto,
					successCb: (res) => {
						uni.hideLoading()
						// 判断数据是否存在
						if (res.data && res.data.list.length > 0) {
							res.data.list.forEach(item => {
								// 商品图片加上前缀
								item.goods_image = item.goods_image.split(',').map(item1 =>
									'https://kx.taipingkeji.com/' + item1)
								// 查看购物车是否有商品 有的话进行数量对换 没有的话 数量复制 0
								if (this.cartData.length > 0) {
									this.cartData.forEach(goodsNum => {
										if (goodsNum.goods_id === item.goods_id) {
											item.currentNum = goodsNum.currentNum
										}
									})
								} else {
									item.currentNum = 0
								}
								// 转换规格 给规格图片加上前缀 判断当前的选择方式是按规格 还是数量
								if (item.goods_spec_format !== '') {
									item.goods_spec_format = JSON.parse(item.goods_spec_format)
									item.materialsFlag = false
								} else {
									item.materialsFlag = true
								}
								item.sku_image = 'https://kx.taipingkeji.com/' + item.sku_image
							})
							this.$refs.paging.complete(res.data.list);
						} else {
							this.$refs.paging.complete(false);
						}
					},
					failCb: (err) => {
						uni.hideLoading()
						this.$refs.paging.complete(false);
					}
				})
			},
			getMenuList() {
				request({
					url: '/kx/Shop/tree',
					method: "POST",
					successCb: (res) => {
						if (res.data.length > 0) {
							this.menuItemPos = res.data
							this.goodsDto.category_id = this.menuItemPos[0].category_id
						} else {
							this.menuItemPos = []
						}
					}
				})
			},
			materialsDetail(val, key) {
				this.productVal = val
				this.productVal.specsData = []
				request({
					url: '/kx/Shop/getInfoForCategory',
					method: "post",
					data: {
						sku_id: val.sku_id
					},
					successCb: (res) => {
						/*
						格式化规格 当购物车有商品时根据规格更新数量 当购物车没有商品
						初始化数量
						*/
						this.productVal.goods_spec_format = JSON.parse(res.data.data.goods_spec_format)
						this.productVal.min_buy ? (this.productVal.currentNum = this.productVal.min_buy) :
							(this.productVal.currentNum = 1)
					}

				})
				this.visibleShow = true
			},

			handleAddToCartInModal(val) {
				// 当用户没选择时 将添加最小购买量
				let flag = false
				if (val.currentNum === 0) {
					uni.$u.toast('请选择购买数量')
					return
				} else {
					this.cartData.forEach(item => {
						if (item.sku_id === val.sku_id) {
							if (val.currentNum + item.currentNum >= item.max_buy && item.max_buy !== 0) {
								flag = true
							} else {
								val.currentNum += item.currentNum
							}
						}
					})
					if (flag) {
						uni.$u.toast('超过最大购买量')
						return
					} else {
						this.handleAddToCart(val)
						this.closeProductDetailModal()
					}
				}
			},

			closeProductDetailModal() {
				this.visibleShow = false
				this.productVal = {}
			},

			// 当前页面添加 判断添加数量是否存在 不存在 赋值 0 存在进行 + 1
			handleCurrentAdd(val) {
				if (!val.currentNum) {
					val.currentNum = 0
				}
				if (val.currentNum >= val.max_buy && val.max_buy !== 0) {
					uni.$u.toast('超过最大购买量')
					return
				}
				if (val.min_buy && val.currentNum === 0) {
					val.currentNum = val.min_buy
				} else {
					val.currentNum += 1
				}
				this.handleAddToCart(val)
			},

			// 添加购物车
			handleAddToCart(val) {
				let flag = this.cartData.findIndex(item => item.sku_id === val.sku_id)
				if (flag === -1) {
					this.cartData.push(val)
				} else {
					this.cartData.forEach(item => {
						if (item.sku_id === val.sku_id) {
							item.currentNum = val.currentNum
						}
					})
				}
				this.dataList.forEach(item => {
					if (item.sku_id === val.sku_id) {
						item.currentNum = val.currentNum
					}
				})
				this.$forceUpdate()
				this.$store.commit('setCard', this.cartData)
			},

			handleMinusFromCart(val) {
				if (val.currentNum === val.min_buy) {
					val.currentNum = 0
					this.cartData.forEach(item => {
						if (item.sku_id === val.sku_id) {
							item.currentNum = val.currentNum
						}
					})
					this.cartData = this.cartData.filter(item => item.currentNum !== 0)
				} else {
					val.currentNum -= 1
					if (val.currentNum) {
						let flag = this.cartData.findIndex(item => item.sku_id === val.sku_id)
						this.cartData[flag].currentNum = val.currentNum
					} else {
						this.cartData.forEach(item => {
							if (item.sku_id === val.sku_id) {
								item.currentNum = val.currentNum
							}
						})
						this.cartData = this.cartData.filter(item => item.currentNum !== 0)
					}
				}
				this.dataList.forEach(item => {
					if (item.sku_id === val.sku_id) {
						item.currentNum = val.currentNum
					}
				})
				this.$forceUpdate()
				this.$store.commit('setCard', this.cartData)
			},
			pay() {
				// 最小购买
				for (let i = 0; i < this.cartData.length; i++) {
					if (this.cartData[i].currentNum < this.cartData[i].min_buy) {
						uni.$u.toast(`${this.cartData[i].goods_name}--最少购买${this.cartData[i].min_buy}`)
						return
					}
				}
				uni.navigateTo({
					url: '/pages/goodsOrder/index'
				})
			},
			handleGoodsDetail(item1) {
				uni.navigateTo({
					url: `/pages/product/index?id=${item1.goods_id}`
				})
			},
			clearCart() {
				this.cartData = []
				this.dataList.forEach(item => item.currentNum = 0)
				this.$store.commit('setCard', this.cartData)
			},
			jumt() {
				uni.navigateTo({
					url: '/pages/goodsSearch/index'
				})
			},
			// 点击左边的栏目切换
			swichMenu(index) {
				this.current = index;
				this.goodsDto.category_id = this.menuItemPos[index].category_id
				this.$refs.paging.reload()
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
						resolve();
					}).exec();
				})
			},
			// 观测元素相交状态
			async observer() {
				this.tabbar.map((val, index) => {
					let observer = uni.createIntersectionObserver(this);
					// 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
					// 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
					observer.relativeTo('.right-box', {
						top: 0
					}).observe('#item' + index, res => {
						if (res.intersectionRatio > 0) {
							let id = res.id.substring(4);
							this.leftMenuStatus(id);
						}
					})
				})
			},
			// 设置左边菜单的滚动状态
			async leftMenuStatus(index) {
				this.current = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('u-tab-item', 'menuItemHeight');
				}
				// 将菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
			},
			// 获取右边菜单每个item到顶部的距离
			getMenuItemTop() {
				new Promise(resolve => {
					let selectorQuery = uni.createSelectorQuery();
					selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
						// 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
						if (!rects.length) {
							setTimeout(() => {
								this.getMenuItemTop();
							}, 10);
							return;
						}
						rects.forEach((rect) => {
							// 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
							this.arr.push(rect.top - rects[0].top);
							resolve();
						})
					}).exec()
				})
			},
			// 右边菜单滚动
			async rightScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (this.timer) return;
				if (!this.menuHeight) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
				}
				setTimeout(() => { // 节流
					this.timer = null;
					// scrollHeight为右边菜单垂直中点位置
					let scrollHeight = e.detail.scrollTop + this.menuHeight / 2;
					for (let i = 0; i < this.arr.length; i++) {
						let height1 = this.arr[i];
						let height2 = this.arr[i + 1];
						// 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
						if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
							this.leftMenuStatus(i);
							return;
						}
					}
				}, 10)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-wrap {
		min-height: calc(92vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
		padding-bottom: calc(env(safe-area-inset-bottom) + 44rpx);
		display: flex;
		flex-direction: column;
	}

	.u-search-box {
		padding: 18rpx 30rpx;
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 200rpx;
		min-height: 90vh;
	}

	.u-tab-item {
		height: 110rpx;
		background: #f6f6f6;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #444;
		font-weight: 400;
		line-height: 1;
	}

	.u-tab-item-active {
		position: relative;
		color: #FF8732;
		font-size: 30rpx;
		font-weight: 600;
		background: #fff;
	}

	.u-tab-item-active::before {
		content: "";
		position: absolute;
		border-left: 4px solid #FF8732;
		height: 32rpx;
		left: 0;
		top: 39rpx;
	}

	.u-tab-view {
		background-color: #f6f6f6;
		height: 100%;
	}

	.right-box {
		background-color: rgb(250, 250, 250);
	}

	.page-view {
		padding: 16rpx;
	}

	.class-item {
		margin-bottom: 30rpx;
		background-color: #fff;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.class-item:last-child {
		min-height: 100vh;
	}

	.item-title {
		font-size: 26rpx;
		color: #303133;
		font-weight: bold;
	}

	.item-menu-name {
		font-weight: normal;
		font-size: 24rpx;
		color: #303133;
	}

	.item-container {
		display: flex;
		flex-wrap: wrap;
	}

	.thumb-box {
		width: 33.333333%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		margin-top: 20rpx;
	}

	.item-menu-image {
		width: 120rpx;
		height: 120rpx;
	}

	.products-list {
		background: #fff;
		padding-top: 24rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 118rpx);

		.category-name {
			padding: 20rpx;
			font-size: 24rpx;
			color: #999;
		}

		.products {
			display: flex;
			flex-direction: column;
			margin-bottom: 20rpx;
		}

		.product {
			display: flex;
			align-items: center;
			padding-bottom: 20rpx;

			.image {
				width: 180rpx;
				height: 135rpx;
				flex-shrink: 0;
				padding: 20rpx;
			}

			.content {
				flex: 1;
				display: flex;
				flex-direction: column;
				overflow: hidden;
				padding-right: 20rpx;

				.name {
					font-size: 26rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					margin-bottom: 8rpx;
				}

				.labels {
					display: flex;
					font-size: 20rpx;
					margin-bottom: 8rpx;
					overflow: hidden;
					flex-wrap: wrap;

					.label {
						max-width: 40%;
						padding: 6rpx 10rpx;
						margin-right: 10rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.description {
					margin-bottom: 20rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
					color: #999;
					font-size: 24rpx;
				}

				.price {
					font-size: 28rpx;
					font-weight: bold;
					display: flex;
					align-items: center;
					justify-content: space-between;
				}
			}
		}
	}

	.ads1 {
		width: 100%;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.mpd {
		padding-bottom: 88rpx !important;
	}
</style>